<?php

namespace DreamCat\FrameCore\Share\Container;

use DreamCat\Container\HelperInfo\RegeditFactory;
use DreamCat\Container\HelperInfo\RegeditInfo;
use DreamCat\Container\HelperInfo\RegeditProp;
use DreamCat\Container\RegeditContainer;
use DreamCat\FrameCore\Factory\Enum\BeanMode;

/**
 * 容器注册bean
 * @author vijay
 */
trait RegeditBean
{
    /**
     * 向容器中注册bean
     * @param string $id beanid
     * @param string|array $beanConfig
     * @param RegeditContainer $container
     * @return RegeditContainer
     */
    protected function regeditBeanIntoContainer(string $id, $beanConfig, RegeditContainer $container): RegeditContainer
    {
        if (!is_array($beanConfig)) {
            $beanConfig = [
                "class" => $beanConfig,
                "mode" => BeanMode::BEAN_MODE_CLASS,
            ];
        } elseif (!isset($beanConfig["mode"])) {
            $beanConfig["mode"] = BeanMode::BEAN_MODE_CLASS;
        }
        $save = $beanConfig["save"] ?? true;
        foreach ($beanConfig["alias"] ?? [] as $alias) {
            $container->regedit($alias, RegeditFactory::regeditClass($id, [], $save));
        }
        $class = $beanConfig["class"] ?? $id;
        $props = $beanConfig["props"] ?? [];
        if ($class != $id || $beanConfig["mode"] == BeanMode::BEAN_MODE_FACTORY || $props || !$save) {
            $regeditInfo = new RegeditInfo(
                $beanConfig["mode"] == BeanMode::BEAN_MODE_FACTORY,
                $class,
                RegeditProp::builderProps($props),
                $save
            );
            $container->regedit($id, $regeditInfo);
        }
        return $container;
    }
}

# end of file
